{
    "cells": [
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {
                    "base_uri": "https://localhost:8080/",
                    "height": 1000
                },
                "colab_type": "code",
                "id": "cvXwyS263AMk",
                "outputId": "57646cdd-58c1-4ddb-8805-9178cb0a2048"
            },
            "outputs": [],
            "source": [
                "\"\"\"\n",
                "You can run either this notebook locally (if you have all the dependencies and a GPU) or on Google Colab.\n",
                "\n",
                "Instructions for setting up Colab are as follows:\n",
                "1. Open a new Python 3 notebook.\n",
                "2. Import this notebook from GitHub (File -> Upload Notebook -> \"GITHUB\" tab -> copy/paste GitHub URL)\n",
                "3. Connect to an instance with a GPU (Runtime -> Change runtime type -> select \"GPU\" for hardware accelerator)\n",
                "4. Run this cell to set up dependencies.\n",
                "\n",
                "\n",
                "NOTE: User is responsible for checking the content of datasets and the applicable licenses and determining if suitable for the intended use.\n",
                "\"\"\"\n",
                "# If you're using Google Colab and not running locally, run this cell.\n",
                "\n",
                "## Install dependencies\n",
                "!pip install wget\n",
                "!apt-get install sox libsndfile1 ffmpeg\n",
                "!pip install text-unidecode\n",
                "\n",
                "# ## Install NeMo\n",
                "BRANCH = 'main'\n",
                "!python -m pip install git+https://github.com/NVIDIA/NeMo.git@$BRANCH#egg=nemo_toolkit[asr]\n",
                "\n",
                "## Install TorchAudio\n",
                "!pip install torchaudio>=0.13.0 -f https://download.pytorch.org/whl/torch_stable.html\n",
                "\n",
                "## Grab the config we'll use in this example\n",
                "!mkdir configs"
            ]
        },
        {
            "attachments": {},
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "Kqg4Rwki4jBX"
            },
            "source": [
                "# Introduction\n",
                "\n",
                "Data augmentation is a useful method to improve the performance of models which is applicable across multiple domains. Certain augmentations can also substantially improve robustness of models to noisy samples. \n",
                "\n",
                "In this notebook, we describe how to construct an augmentation pipeline inside [Neural Modules (NeMo)](https://github.com/NVIDIA/NeMo), enable augmented training of a [MatchboxNet model](https://arxiv.org/abs/2004.08531 ) ( based on QuartzNet, from the paper [\"QuartzNet: Deep Automatic Speech Recognition with 1D Time-Channel Separable Convolutions\"](https://arxiv.org/abs/1910.10261)) and finally how to construct custom augmentations to add to NeMo.\n",
                "\n",
                "The notebook will follow the steps below:\n",
                "\n",
                " - Dataset preparation: Preparing a noise dataset using an example file.\n",
                "\n",
                " - Construct a data augmentation pipeline.\n",
                " \n",
                " - Construct a custom augmentation and register it for use in NeMo."
            ]
        },
        {
            "attachments": {},
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "5XieMEo84pJ-"
            },
            "source": [
                "## Note\n",
                "Data augmentation is valuable for many datasets, but it comes at the cost of increased training time if samples are augmented during training time. Certain augmentations are particularly costly, in terms of how much time they take to process a single sample. A few examples of slow augmentations available in NeMo are : \n",
                "\n",
                " - Speed Perturbation\n",
                " - Time Stretch Perturbation (Sample level)\n",
                " - Noise Perturbation\n",
                " - Impulse Perturbation\n",
                " - Time Stretch Augmentation (Batch level, Neural Module)\n",
                " \n",
                "For such augmentations, it is advisable to pre-process the dataset offline for a one time preprocessing cost and then train the dataset on this augmented training set."
            ]
        },
        {
            "attachments": {},
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "Tgc_ZHDl4sMy"
            },
            "source": [
                "## Taking a Look at Our Data (AN4)\n",
                "\n",
                "The AN4 dataset, also known as the Alphanumeric dataset, was collected and published by Carnegie Mellon University. It consists of recordings of people spelling out addresses, names, telephone numbers, etc., one letter or number at a time, as well as their corresponding transcripts. We choose to use AN4 for this tutorial because it is relatively small, with 948 training and 130 test utterances, and so it trains quickly.\n",
                "\n",
                "Before we get started, let's download and prepare the dataset. The utterances are available as `.sph` files, so we will need to convert them to `.wav` for later processing. Please make sure you have [Sox](http://sox.sourceforge.net/) installed for this step (instructions to setup your environment are available at the beginning of this notebook)."
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "DtLm_XuQ3pmk"
            },
            "outputs": [],
            "source": [
                "# This is where the an4/ directory will be placed.\n",
                "# Change this if you don't want the data to be extracted in the current directory.\n",
                "data_dir = '.'"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {
                    "base_uri": "https://localhost:8080/",
                    "height": 102
                },
                "colab_type": "code",
                "id": "HjfLhUtH4wNc",
                "outputId": "f0a9cd46-6709-49dd-9103-1e0ef61de745"
            },
            "outputs": [],
            "source": [
                "import glob\n",
                "import os\n",
                "import subprocess\n",
                "import tarfile\n",
                "import wget\n",
                "\n",
                "# Download the dataset. This will take a few moments...\n",
                "print(\"******\")\n",
                "if not os.path.exists(data_dir + '/an4_sphere.tar.gz'):\n",
                "    an4_url = 'https://dldata-public.s3.us-east-2.amazonaws.com/an4_sphere.tar.gz'\n",
                "    an4_path = wget.download(an4_url, data_dir)\n",
                "    print(f\"Dataset downloaded at: {an4_path}\")\n",
                "else:\n",
                "    print(\"Tarfile already exists.\")\n",
                "    an4_path = data_dir + '/an4_sphere.tar.gz'\n",
                "\n",
                "if not os.path.exists(data_dir + '/an4/'):\n",
                "    # Untar and convert .sph to .wav (using sox)\n",
                "    tar = tarfile.open(an4_path)\n",
                "    tar.extractall(path=data_dir)\n",
                "\n",
                "    print(\"Converting .sph to .wav...\")\n",
                "    sph_list = glob.glob(data_dir + '/an4/**/*.sph', recursive=True)\n",
                "    for sph_path in sph_list:\n",
                "        wav_path = sph_path[:-4] + '.wav'\n",
                "        cmd = [\"sox\", sph_path, wav_path]\n",
                "        subprocess.run(cmd)\n",
                "print(\"Finished conversion.\\n******\")\n"
            ]
        },
        {
            "attachments": {},
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "HqJmf4WB5P1x"
            },
            "source": [
                "You should now have a folder called `an4` that contains `etc/an4_train.transcription`, `etc/an4_test.transcription`, audio files in `wav/an4_clstk` and `wav/an4test_clstk`, along with some other files we will not need.\n",
                "\n",
                "We now build a few manifest files which will be used later:"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {
                    "base_uri": "https://localhost:8080/",
                    "height": 85
                },
                "colab_type": "code",
                "id": "AmR6CH025C8E",
                "outputId": "0cd776ea-078f-4ab8-8a79-eed3e1c05839"
            },
            "outputs": [],
            "source": [
                "# --- Building Manifest Files --- #\n",
                "import json\n",
                "import librosa\n",
                "\n",
                "# Function to build a manifest\n",
                "def build_manifest(transcripts_path, manifest_path, wav_path):\n",
                "    with open(transcripts_path, 'r') as fin:\n",
                "        with open(manifest_path, 'w') as fout:\n",
                "            for line in fin:\n",
                "                # Lines look like this:\n",
                "                # <s> transcript </s> (fileID)\n",
                "                transcript = line[: line.find('(')-1].lower()\n",
                "                transcript = transcript.replace('<s>', '').replace('</s>', '')\n",
                "                transcript = transcript.strip()\n",
                "\n",
                "                file_id = line[line.find('(')+1 : -2]  # e.g. \"cen4-fash-b\"\n",
                "                audio_path = os.path.join(\n",
                "                    data_dir, wav_path,\n",
                "                    file_id[file_id.find('-')+1 : file_id.rfind('-')],\n",
                "                    file_id + '.wav')\n",
                "\n",
                "                duration = librosa.core.get_duration(filename=audio_path)\n",
                "\n",
                "                # Write the metadata to the manifest\n",
                "                metadata = {\n",
                "                    \"audio_filepath\": audio_path,\n",
                "                    \"duration\": duration,\n",
                "                    \"text\": transcript\n",
                "                }\n",
                "                json.dump(metadata, fout)\n",
                "                fout.write('\\n')\n",
                "                \n",
                "# Building Manifests\n",
                "print(\"******\")\n",
                "train_transcripts = data_dir + '/an4/etc/an4_train.transcription'\n",
                "train_manifest = data_dir + '/an4/train_manifest.json'\n",
                "build_manifest(train_transcripts, train_manifest, 'an4/wav/an4_clstk')\n",
                "print(\"Training manifest created.\")\n",
                "\n",
                "test_transcripts = data_dir + '/an4/etc/an4_test.transcription'\n",
                "test_manifest = data_dir + '/an4/test_manifest.json'\n",
                "build_manifest(test_transcripts, test_manifest, 'an4/wav/an4test_clstk')\n",
                "print(\"Test manifest created.\")\n",
                "print(\"******\")"
            ]
        },
        {
            "attachments": {},
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "EQsXzh7x5zIQ"
            },
            "source": [
                "## Prepare the path to manifest files"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "vmOa0IRC5eW4"
            },
            "outputs": [],
            "source": [
                "dataset_basedir = os.path.join(data_dir, 'an4')\n",
                "\n",
                "train_dataset = os.path.join(dataset_basedir, 'train_manifest.json')\n",
                "test_dataset = os.path.join(dataset_basedir, 'test_manifest.json')"
            ]
        },
        {
            "attachments": {},
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "pz9LC3yZ6J1Q"
            },
            "source": [
                "## Read a few rows of the manifest file \n",
                "\n",
                "Manifest files are the data structure used by NeMo to declare a few important details about the data :\n",
                "\n",
                "1) `audio_filepath`: Refers to the path to the raw audio file <br>\n",
                "2) `text`: The text transcript of this sample <br>\n",
                "3) `duration`: The length of the audio file, in seconds."
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "3OzZQiX751iz"
            },
            "outputs": [],
            "source": [
                "!head -n 5 {train_dataset}"
            ]
        },
        {
            "attachments": {},
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "pD9bprV66Oai"
            },
            "source": [
                "# Data Augmentation Pipeline\n",
                "\n",
                "Constructing a data augmentation pipeline in NeMo is as simple as composing a nested dictionary that describes two things :\n",
                "\n",
                "1) The probability of that augmentation occurring - using the `prob` keyword <br>\n",
                "2) The keyword arguments required by that augmentation class\n",
                "\n",
                "Below, we show a few samples of these augmentations. Note, in order to distinguish between the original sample and the perturbed sample, we exaggerate the perturbation strength significantly."
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "l5bc7gYO6MHG"
            },
            "outputs": [],
            "source": [
                "import torch\n",
                "import IPython.display as ipd"
            ]
        },
        {
            "attachments": {},
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "L8Bd8s3e6TeK"
            },
            "source": [
                "## Audio file preparation "
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "g7f9riZz6Qnj"
            },
            "outputs": [],
            "source": [
                "# Import the data augmentation component from ASR collection\n",
                "from nemo.collections.asr.parts.preprocessing import perturb, segment"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "wK8uwpt16d6I"
            },
            "outputs": [],
            "source": [
                "# Lets see the available perturbations\n",
                "perturb.perturbation_types"
            ]
        },
        {
            "attachments": {},
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "IP1VpkOA6nE-"
            },
            "source": [
                "### Obtain a baseline audio file"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "sj4DNMmZ6ktm"
            },
            "outputs": [],
            "source": [
                "filepath = librosa.util.example(key='vibeace', hq=True)\n",
                "sample, sr = librosa.core.load(filepath)\n",
                "\n",
                "ipd.Audio(sample, rate=sr)"
            ]
        },
        {
            "attachments": {},
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "M9mZNm296tNf"
            },
            "source": [
                "### Convert to WAV format"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "QDjlgLc-6vtq"
            },
            "outputs": [],
            "source": [
                "import soundfile as sf\n",
                "\n",
                "# lets convert this ogg file into a wave to be compatible with NeMo\n",
                "if not os.path.exists('./media'):\n",
                "    os.makedirs('./media/')\n",
                "    \n",
                "filename = 'Kevin_MacLeod_-_Vibe_Ace.wav'\n",
                "filepath = os.path.join('media', filename)\n",
                "\n",
                "sf.write(filepath, sample, samplerate=sr)"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "FEkV-ikT6xgB"
            },
            "outputs": [],
            "source": [
                "sample, sr = librosa.core.load(filepath)\n",
                "ipd.Audio(sample, rate=sr)"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "gmuwEwIQ6zK3"
            },
            "outputs": [],
            "source": [
                "# NeMo has its own support class for loading wav files\n",
                "def load_audio() -> segment.AudioSegment:\n",
                "    filename = 'Kevin_MacLeod_-_Vibe_Ace.wav'\n",
                "    filepath = os.path.join('media', filename)\n",
                "    sample_segment = segment.AudioSegment.from_file(filepath, target_sr=sr)\n",
                "    return sample_segment\n",
                "\n",
                "sample_segment = load_audio()\n",
                "ipd.Audio(sample_segment.samples, rate=sr)"
            ]
        },
        {
            "attachments": {},
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "hTnf1g1y63wZ"
            },
            "source": [
                "## White Noise Perturbation\n",
                "\n",
                "White Noise perturbation is performed by the following steps : <br>\n",
                "1) Randomly sample the amplitude of the noise from a uniformly distributed range (defined in dB) <br>\n",
                "2) Sample gaussian noise (mean = 0, std = 1) with same length as audio signal <br>\n",
                "3) Scale this gaussian noise by the amplitude (in dB scale) <br>\n",
                "4) Add this noise vector to the original sample\n",
                "\n",
                "Notably, the original signal should not have a \"hissing sound\" constantly present in the perturbed version."
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "2jaPQyUY65ij"
            },
            "outputs": [],
            "source": [
                "white_noise = perturb.WhiteNoisePerturbation(min_level=-50, max_level=-30)\n",
                "\n",
                "# Perturb the audio file\n",
                "sample_segment = load_audio()\n",
                "white_noise.perturb(sample_segment)\n",
                "\n",
                "ipd.Audio(sample_segment.samples, rate=sr)"
            ]
        },
        {
            "attachments": {},
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "2dfwesJU7DhN"
            },
            "source": [
                "## Shift Perturbation\n",
                "\n",
                "Shift perturbation is performed by the following steps : <br>\n",
                "1) Randomly sample the shift factor of the signal from a uniformly distributed range (defined in milliseconds) <br>\n",
                "2) Depending on the sign of the shift, we shift the original signal to the left or the right. <br>\n",
                "3) The boundary locations are filled with zeros after the shift of the signal <br>\n",
                "\n",
                "Notably, the perturbed signal below skips the first 25 to 50 seconds of the original audio below, and the remainder of the time is simply silence. "
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "2ONq8dBI7BZf"
            },
            "outputs": [],
            "source": [
                "shift = perturb.ShiftPerturbation(min_shift_ms=25000.0, max_shift_ms=50000.0)\n",
                "\n",
                "# Perturb the audio file \n",
                "sample_segment = load_audio()\n",
                "shift.perturb(sample_segment)\n",
                "\n",
                "ipd.Audio(sample_segment.samples, rate=sr)"
            ]
        },
        {
            "attachments": {},
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "kywA3h4T7G_S"
            },
            "source": [
                "## Data Dependent Perturbations\n",
                "\n",
                "Some perturbations require an external data source in order to perturb the original sample. Noise Perturbation is a perfect example of one such augmentation that requires an external noise source dataset in order to perturb the original data."
            ]
        },
        {
            "attachments": {},
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "eYm2DgGQ7KPe"
            },
            "source": [
                "### Preparing a manifest of \"noise\" samples"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "RXZ1o85E7FLT"
            },
            "outputs": [],
            "source": [
                "# Lets prepare a manifest file using the baseline file itself, cut into 1 second segments\n",
                "\n",
                "def write_manifest(filepath, data_dir='./media/', manifest_name='noise_manifest', duration_max=None, duration_stride=1.0, filter_long=False, duration_limit=10.0):\n",
                "    if duration_max is None:\n",
                "        duration_max = 1e9\n",
                "                \n",
                "    with open(os.path.join(data_dir, manifest_name + '.json'), 'w') as fout:\n",
                "        \n",
                "        try:\n",
                "            duration = librosa.get_duration(filename=filepath)\n",
                "\n",
                "        except Exception:\n",
                "            print(f\"\\n>>>>>>>>> WARNING: Librosa failed to load file {filepath}. Skipping this file !\\n\")\n",
                "            return\n",
                "\n",
                "        if filter_long and duration > duration_limit:\n",
                "            print(f\"Skipping sound sample {filepath}, exceeds duration limit of {duration_limit}\")\n",
                "            return\n",
                "\n",
                "        offsets = []\n",
                "        durations = []\n",
                "\n",
                "        if duration > duration_max:\n",
                "            current_offset = 0.0\n",
                "\n",
                "            while current_offset < duration:\n",
                "                difference = duration - current_offset\n",
                "                segment_duration = min(duration_max, difference)\n",
                "\n",
                "                offsets.append(current_offset)\n",
                "                durations.append(segment_duration)\n",
                "\n",
                "                current_offset += duration_stride\n",
                "\n",
                "        else:\n",
                "            offsets.append(0.0)\n",
                "            durations.append(duration)\n",
                "\n",
                "\n",
                "        for duration, offset in zip(durations, offsets):\n",
                "            metadata = {\n",
                "                'audio_filepath': filepath,\n",
                "                'duration': duration,\n",
                "                'label': 'noise',\n",
                "                'text': '_',  # for compatibility with ASRAudioText collection\n",
                "                'offset': offset,\n",
                "            }\n",
                "\n",
                "            json.dump(metadata, fout)\n",
                "            fout.write('\\n')\n",
                "            fout.flush()\n",
                "\n",
                "        print(f\"Wrote {len(durations)} segments for filename {filename}\")\n",
                "            \n",
                "    print(\"Finished preparing manifest !\")"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "wLTT8jlP7NdU"
            },
            "outputs": [],
            "source": [
                "filename = 'Kevin_MacLeod_-_Vibe_Ace.wav'\n",
                "filepath = os.path.join('media', filename)\n",
                "\n",
                "# Write a \"noise\" manifest file\n",
                "write_manifest(filepath, manifest_name='noise_1s', duration_max=1.0, duration_stride=1.0)"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "izbdrSmd7PY5"
            },
            "outputs": [],
            "source": [
                "# Lets read this noise manifest file\n",
                "noise_manifest_path = os.path.join('media', 'noise_1s.json')\n",
                "\n",
                "!head -n 5 {noise_manifest_path}"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "82yq0TOV7Q_4"
            },
            "outputs": [],
            "source": [
                "# Lets create a helper method to load the first file in the train dataset of AN4\n",
                "# Load the first sample in the manifest\n",
                "def load_gsc_sample() -> segment.AudioSegment:\n",
                "    with open(train_dataset, 'r') as f:\n",
                "        line = f.readline()\n",
                "        \n",
                "    line = json.loads(line)\n",
                "    gsc_filepath = line['audio_filepath']\n",
                "    sample_segment = segment.AudioSegment.from_file(gsc_filepath)\n",
                "    return sample_segment\n",
                "\n",
                "gsc_sample_segment = load_gsc_sample()\n",
                "ipd.Audio(gsc_sample_segment.samples, rate=16000)"
            ]
        },
        {
            "attachments": {},
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "zV9ypBqz7V9a"
            },
            "source": [
                "## Noise Augmentation\n",
                "\n",
                "Noise perturbation is performed by the following steps : <br>\n",
                "1) Randomly sample the amplitude scale of the noise sample from a uniformly distributed range (defined in dB) <br>\n",
                "2) Randomly choose an audio clip from the set of noise audio samples available <br>\n",
                "3) Compute the gain (in dB) required for the noise clip as compared to the original sample and scale the noise by this factor <br>\n",
                "4) If the noise snippet is of shorter duration than the original audio, then randomly select an index in time from the original sample, where the noise snippet will be added <br>\n",
                "5) If instead the noise snippet is longer than the duration of the original audio, then randomly subsegment the noise snippet and add the full snippet to the original audio <br>\n",
                "\n",
                "Notably, the noise perturbed sample should sound as if there are two sounds playing at the same time (overlapping audio) as compared to the original signal. The magnitude of the noise will be dependent on step (3) and the location where the noise is added will depend on steps (4) and (5)."
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "cjSXci1v7Tlg"
            },
            "outputs": [],
            "source": [
                "import random\n",
                "rng = 42 #note you can use integer to be as random seed to reproduce result \n",
                "noise = perturb.NoisePerturbation(manifest_path=noise_manifest_path,\n",
                "                                  min_snr_db=-10, max_snr_db=-10,\n",
                "                                  max_gain_db=300.0, rng=rng)\n",
                "\n",
                "# Perturb the audio file \n",
                "sample_segment = load_gsc_sample()\n",
                "noise.perturb(sample_segment)\n",
                "\n",
                "ipd.Audio(sample_segment.samples, rate=16000)"
            ]
        },
        {
            "attachments": {},
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "## RIR and Noise Perturbation\n",
                "RIR augmentation with additive foreground and background noise.\n",
                "In this implementation audio data is augmented by first convolving the audio with a Room Impulse Response\n",
                "and then adding foreground noise and background noise at various SNRs. RIR, foreground and background noises\n",
                "should either be supplied with a manifest file or as tarred audio files (faster)."
            ]
        },
        {
            "attachments": {},
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "### Prepare rir data and manifest"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {},
            "outputs": [],
            "source": [
                "# This is where the rir data will be downloaded.\n",
                "# Change this if you don't want the data to be extracted in the current directory.\n",
                "!wget https://raw.githubusercontent.com/NVIDIA/NeMo/$BRANCH/scripts/dataset_processing/get_openslr_rir_data.py\n",
                "rir_data_path = '.'\n",
                "!python get_openslr_rir_data.py --data_root {rir_data_path}\n",
                "rir_manifest_path = os.path.join(rir_data_path, 'processed', 'rir.json')\n",
                "!head -n 3 {rir_manifest_path}"
            ]
        },
        {
            "attachments": {},
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "### Create RIR instance"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {},
            "outputs": [],
            "source": [
                "rir = perturb.RirAndNoisePerturbation(rir_manifest_path=rir_manifest_path, \n",
                "                                      rir_prob=1,\n",
                "                                      noise_manifest_paths=[noise_manifest_path], # use noise_manifest_path from previous step\n",
                "                                      bg_noise_manifest_paths=[noise_manifest_path],\n",
                "                                      min_snr_db=[20], # foreground noise snr\n",
                "                                      max_snr_db=[20],\n",
                "                                      bg_min_snr_db=[20], # background noise snr\n",
                "                                      bg_max_snr_db=[20],\n",
                "                                      noise_tar_filepaths=[None], # `[None]` to indicates that noise audio files are not tar.\n",
                "                                      bg_noise_tar_filepaths=[None])"
            ]
        },
        {
            "attachments": {},
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "### Perturb the audio"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {},
            "outputs": [],
            "source": [
                "sample_segment = load_gsc_sample()\n",
                "rir.perturb(sample_segment)\n",
                "ipd.Audio(sample_segment.samples, rate=16000)"
            ]
        },
        {
            "attachments": {},
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "kJjUkGJu7ern"
            },
            "source": [
                "## Speed Perturbation\n",
                "\n",
                "Speed perturbation changes the speed of the speech, but does not preserve pitch of the sound. Try a few random augmentations to see how the pitch changes with change in duration of the audio file.\n",
                "\n",
                "**Note**: This is a very slow augmentation and is not advised to perform online augmentation for large datasets as it can dramatically increase training time."
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "Ic-ziInU7ZKC"
            },
            "outputs": [],
            "source": [
                "resample_type = 'kaiser_best'  # Can be ['kaiser_best', 'kaiser_fast', 'fft', 'scipy']\n",
                "speed = perturb.SpeedPerturbation(sr, resample_type, min_speed_rate=0.5, max_speed_rate=2.0, num_rates=-1)\n",
                "\n",
                "# Perturb the audio file \n",
                "sample_segment = load_gsc_sample()\n",
                "speed.perturb(sample_segment)\n",
                "\n",
                "ipd.Audio(sample_segment.samples, rate=16000)"
            ]
        },
        {
            "attachments": {},
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "bhHX3dyh7jPq"
            },
            "source": [
                "## Time Stretch Perturbation\n",
                "\n",
                "Time Stretch perturbation changes the speed of the speech, and also preserve pitch of the sound. \n",
                "Try a few random augmentations to see how the pitch remains close to the same with change in duration of the audio file."
            ]
        },
        {
            "attachments": {},
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "8_kNSfcK7lfP"
            },
            "source": [
                "### Note about speed optimizations\n",
                "\n",
                "Time stretch is a costly augmentation, and can easily cause training time to increase drastically. It is suggested that one installs the `numba` library using conda to use a more optimized augmentation kernel.\n",
                "\n",
                "```python\n",
                "conda install numba\n",
                "```"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "Dpeb0QUZ7g3l"
            },
            "outputs": [],
            "source": [
                "time_stretch = perturb.TimeStretchPerturbation(min_speed_rate=0.5, max_speed_rate=2.0, num_rates=3)\n",
                "\n",
                "# Perturb the audio file \n",
                "sample_segment = load_gsc_sample()\n",
                "time_stretch.perturb(sample_segment)\n",
                "\n",
                "ipd.Audio(sample_segment.samples, rate=16000)"
            ]
        },
        {
            "attachments": {},
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "vhH1-Ga87rCX"
            },
            "source": [
                "# Augmentation Pipeline\n",
                "\n",
                "The augmentation pipeline can be constructed in multiple ways, either explicitly by instantiating the objects of these perturbations or implicitly by providing the arguments to these augmentations as a nested dictionary.\n",
                "\n",
                "We will show both approaches in the following sections"
            ]
        },
        {
            "attachments": {},
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "RC8_NOD97tlW"
            },
            "source": [
                "## Explicit definition"
            ]
        },
        {
            "attachments": {},
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "UwWE7swo72WP"
            },
            "source": [
                "### Instantiate the perturbations"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "GdLYn0hx7pRU"
            },
            "outputs": [],
            "source": [
                "perturbations = [\n",
                "    perturb.WhiteNoisePerturbation(min_level=-90, max_level=-46),\n",
                "    perturb.GainPerturbation(min_gain_dbfs=0, max_gain_dbfs=50),\n",
                "    perturb.NoisePerturbation(manifest_path=noise_manifest_path,\n",
                "                              min_snr_db=0, max_snr_db=50, max_gain_db=300.0)\n",
                "]"
            ]
        },
        {
            "attachments": {},
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "CDSSbZ8w7zzR"
            },
            "source": [
                "### Select chance of perturbations being applied"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "NmoxfLSL7xPJ"
            },
            "outputs": [],
            "source": [
                "probas = [1.0, 1.0, 0.5]"
            ]
        },
        {
            "attachments": {},
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "wl0tnrMq79Jh"
            },
            "source": [
                "### Prepare the audio augmentation object"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "nO6T4U4f767o"
            },
            "outputs": [],
            "source": [
                "augmentations = list(zip(probas, perturbations))\n",
                "\n",
                "audio_augmentations = perturb.AudioAugmentor(augmentations)\n",
                "audio_augmentations._pipeline"
            ]
        },
        {
            "attachments": {},
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "9cgI9yUx8Cyv"
            },
            "source": [
                "## Implicit definition\n",
                "\n",
                "Implicit definitions are preferred since they can be prepared in the actual configuration object."
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "tiqrKFTM7_mH"
            },
            "outputs": [],
            "source": [
                "perturb.perturbation_types  # Available perturbations"
            ]
        },
        {
            "attachments": {},
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "dbeXwLdw8VEc"
            },
            "source": [
                "### Prepare the nested dictionary"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "mbE0qEA98TRI"
            },
            "outputs": [],
            "source": [
                "audio_augmentations = dict(\n",
                "    white_noise = dict(\n",
                "        prob=1.0,\n",
                "        min_level=-90,\n",
                "        max_level=-46\n",
                "    ),\n",
                "    gain = dict(\n",
                "        prob=1.0,\n",
                "        min_gain_dbfs=0,\n",
                "        max_gain_dbfs=50\n",
                "    ),\n",
                "    noise = dict(\n",
                "        prob=0.5,\n",
                "        manifest_path=noise_manifest_path,\n",
                "        min_snr_db=0,\n",
                "        max_snr_db=50,\n",
                "        max_gain_db=300.0\n",
                "    )\n",
                ")\n",
                "\n",
                "audio_augmentations"
            ]
        },
        {
            "attachments": {},
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "tcsoCe9-8ZM9"
            },
            "source": [
                "### Supply `augmentor` as an argument to the `model.train_ds` config\n",
                "\n",
                "Most of the common datasets used by ASR models support the keyword `augmentor` - which can include a nested dictionary defining the implicit definition of an augmentation pipeline.\n",
                "\n",
                "Note, all ASR models support implicit declaration of augmentations. This includes - \n",
                "\n",
                "1) Speech To Label Models <br>\n",
                "2) Speech To Text Models <br>\n",
                "3) Speech To Text Models with BPE/WPE Support<br>"
            ]
        },
        {
            "attachments": {},
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "0WOJC0fdBL5J"
            },
            "source": [
                "# Training - Application of augmentations\n",
                "\n",
                "We will be describing the data loaders for a MatchboxNet model from the paper \"[MatchboxNet: 1D Time-Channel Separable Convolutional Neural Network Architecture for Speech Commands Recognition](https://arxiv.org/abs/2004.08531)\". The benefit of MatchboxNet over JASPER models is that they use Separable Convolutions, which greatly reduce the number of parameters required to get good model accuracy.\n",
                "\n",
                "<ins>Care must be taken not to apply augmentations to the test set!</ins>\n"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "7iDWiIrzBzUA"
            },
            "outputs": [],
            "source": [
                "from omegaconf import OmegaConf"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "yv3KWNjcAUnQ"
            },
            "outputs": [],
            "source": [
                "# We will download the MatchboxNet configuration file for either v1 or v2 dataset here\n",
                "DATASET_VER = 1\n",
                "\n",
                "if DATASET_VER == 1:\n",
                "  MODEL_CONFIG = \"matchboxnet_3x1x64_v1.yaml\"\n",
                "else:\n",
                "  MODEL_CONFIG = \"matchboxnet_3x1x64_v2.yaml\"\n",
                "\n",
                "if not os.path.exists(f\"configs/{MODEL_CONFIG}\"):\n",
                "  !wget -P configs/ \"https://raw.githubusercontent.com/NVIDIA/NeMo/$BRANCH/examples/asr/conf/matchboxnet/{MODEL_CONFIG}\""
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "vOcv0ri3BkmA"
            },
            "outputs": [],
            "source": [
                "# This line will load the entire config of the MatchboxNet model\n",
                "config_path = f\"configs/{MODEL_CONFIG}\"\n",
                "config = OmegaConf.load(config_path)"
            ]
        },
        {
            "attachments": {},
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "mLsyceMSCIHV"
            },
            "source": [
                "### Augmentation in train set only\n",
                "\n",
                "Note how the train dataset config supports the `augmentor` implicit definition, however the test config does not.\n",
                "\n",
                "This is essential to avoid mistakenly performing Test Time Augmentation."
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "VgUVm7lGB8Cz"
            },
            "outputs": [],
            "source": [
                "# Has `augmentor`\n",
                "print(OmegaConf.to_yaml(config.model.train_ds))"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "gURwQ2eyCE7o"
            },
            "outputs": [],
            "source": [
                "# Does not have `augmentor`\n",
                "print(OmegaConf.to_yaml(config.model.test_ds))"
            ]
        },
        {
            "attachments": {},
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "_UV74AVlCo_m"
            },
            "source": [
                "# Custom Perturbations\n",
                "\n",
                "We can define and use custom perturbations as required simply by extending the `Perturbation` class. \n",
                "\n",
                "Let's look at how we can build a custom Noise Perturbation that we can use to evaluate the effect of noise at inference time, in order to measure the model's robustness to noise\n",
                "\n",
                "In evaluation mode, we want to set an explicit value for the `snr_db` parameter instead of uniformly sample it from a range. This allows us to control the signal to noise ratio without relying on randomness from the training implementation of `NoisePerturbation`.\n",
                "\n",
                "Further, we force a random seed in order to produce reproduceable results on the evaluation set.\n",
                "\n",
                "With this combination, we can easily evaluate each sample in the test set `S` times (`S` being the number of random seeds), and can evaluate each of these samples at `D` levels of Signal to Noise Ratio (in dB). "
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "Q9YBmBiZCbAX"
            },
            "outputs": [],
            "source": [
                "# We use a NeMo utility to parse the manifest file for us\n",
                "from nemo.collections.common.parts.preprocessing import collections, parsers\n",
                "\n",
                "class NoisePerturbationEval(perturb.Perturbation):\n",
                "    def __init__(\n",
                "        self, manifest_path=None, snr_db=40, max_gain_db=300.0, rng=None,\n",
                "    ):\n",
                "        self._manifest = collections.ASRAudioText(manifest_path, parser=parsers.make_parser([]))\n",
                "        self._snr_db = snr_db\n",
                "        self._max_gain_db = max_gain_db\n",
                "        random.seed(rng) if rng else None\n",
                "    \n",
                "    # This is mostly obtained from the original NoisePerturbation class itself\n",
                "    def perturb(self, data):\n",
                "        snr_db = self._snr_db\n",
                "        noise_record = random.sample(self._manifest.data, 1)[0]\n",
                "        noise = AudioSegment.from_file(noise_record.audio_file, target_sr=data.sample_rate)\n",
                "        noise_gain_db = min(data.rms_db - noise.rms_db - snr_db, self._max_gain_db)\n",
                "\n",
                "        # calculate noise segment to use\n",
                "        start_time = 0.0\n",
                "        if noise.duration > (start_time + data.duration):\n",
                "            noise.subsegment(start_time=start_time, end_time=start_time + data.duration)\n",
                "\n",
                "        # adjust gain for snr purposes and superimpose\n",
                "        noise.gain_db(noise_gain_db)\n",
                "\n",
                "        if noise._samples.shape[0] < data._samples.shape[0]:\n",
                "            noise_idx = data._samples.shape[0] // 2  # midpoint of audio\n",
                "            while (noise_idx + noise._samples.shape[0]) > data._samples.shape[0]:\n",
                "                noise_idx = noise_idx // 2  # half the initial starting point\n",
                "\n",
                "            data._samples[noise_idx: noise_idx + noise._samples.shape[0]] += noise._samples\n",
                "\n",
                "        else:\n",
                "            data._samples += noise._samples\n"
            ]
        },
        {
            "attachments": {},
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "qR8qiwSkC1eE"
            },
            "source": [
                "## Registering augmentations\n",
                "\n",
                "We can use either approach to submit this test time augmentation to the Data Loaders.\n",
                "\n",
                "In order to obtain the convenience of the implicit method, we must register this augmentation into NeMo's directory of available augmentations. This can be done as follows -"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "40Z4Fm88CxWA"
            },
            "outputs": [],
            "source": [
                "perturb.register_perturbation(name='noise_eval', perturbation=NoisePerturbationEval)"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {
                "colab": {},
                "colab_type": "code",
                "id": "jVVbRxb-C4hB"
            },
            "outputs": [],
            "source": [
                "# Lets check the registry of allowed perturbations !\n",
                "perturb.perturbation_types"
            ]
        },
        {
            "attachments": {},
            "cell_type": "markdown",
            "metadata": {
                "colab_type": "text",
                "id": "2fiHz6CdC-B1"
            },
            "source": [
                "## Overriding pre-existing augmentations\n",
                "\n",
                "**Note**: It is not allowed to overwrite already registered perturbations using the `perturb.register_perturbation` method. It will raise a `ValueError` in order to prevent overwriting the pre-existing perturbation types"
            ]
        }
    ],
    "metadata": {
        "accelerator": "GPU",
        "colab": {
            "collapsed_sections": [],
            "name": "Online_Noise_Augmentation.ipynb",
            "provenance": [],
            "toc_visible": true
        },
        "kernelspec": {
            "display_name": "Python 3",
            "language": "python",
            "name": "python3"
        },
        "language_info": {
            "codemirror_mode": {
                "name": "ipython",
                "version": 3
            },
            "file_extension": ".py",
            "mimetype": "text/x-python",
            "name": "python",
            "nbconvert_exporter": "python",
            "pygments_lexer": "ipython3",
            "version": "3.7.7"
        },
        "pycharm": {
            "stem_cell": {
                "cell_type": "raw",
                "metadata": {
                    "collapsed": false
                },
                "source": []
            }
        }
    },
    "nbformat": 4,
    "nbformat_minor": 4
}
